package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.StackProblem;
import joptsimple.internal.Strings;

import java.util.LinkedList;

/**
 * 还是有点啰嗦, 链接中python写的很简洁
 * https://leetcode.com/problems/decode-string/discuss/87662/Python-solution-using-stack
 *
 * @author tzp
 * @since 2020/10/17
 */
public class LC394_1 implements StackProblem {

    public String decodeString(String s) {
        if (s == null || s.length() == 0) return "";
        LinkedList<Object> list = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            if (']' != s.charAt(i)) {
                list.addLast(s.charAt(i));
            } else if (']' == s.charAt(i)) {
                StringBuilder repeatContent = new StringBuilder();
                Object o;
                //弹出直到左括号
                while (!((o = list.pollLast()) instanceof Character) || ((Character) o) != '[') {
                    repeatContent.insert(0, o);
                }
                StringBuilder repeatTime = new StringBuilder();
                //弹出直到非数字
                while (((o = list.peekLast()) instanceof Character) &&
                        ((Character) o >= '0' && (Character) o <= '9')) {
                    repeatTime.insert(0, o);
                    list.removeLast();
                }
                StringBuilder content = new StringBuilder();
                for (int j = 0; j < Integer.parseInt(repeatTime.toString()); j++) {
                    content.append(repeatContent.toString());
                }
                list.addLast(content.toString());
            }
        }
        StringBuilder result = new StringBuilder();
        while (list.size() >0) {
            result.insert(0, list.pollLast().toString());
        }
        return result.toString();
    }

    public static void main(String[] args) {
        System.out.println(new LC394_1().decodeString("4[a]2[bc]"));
        System.out.println(new LC394_1().decodeString("x3[a2[c]]"));//"xaccaccacc"
    }
}
